package com.qf.day6;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * @date 2022/4/2
 * @desc
 */
@WebListener
public class MyHttpSessionListener implements HttpSessionListener {

    int onLineNumber=0;
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        System.out.println("session创建了");

        //把当前在线人数 放在  servletContext 域对象

        ServletContext servletContext = se.getSession().getServletContext();
        if(servletContext.getAttribute("onLineNumber")==null){
            onLineNumber= 1;
            servletContext.setAttribute("onLineNumber",onLineNumber);
        }else{
            onLineNumber++;
            servletContext.setAttribute("onLineNumber",onLineNumber);
        }

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("session销毁了");

        ServletContext servletContext = se.getSession().getServletContext();
        //销毁一个session 说明下线一个
        servletContext.setAttribute("onLineNumber",--onLineNumber);
    }
}
